package com.example.cloudzuul.web;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

//@Component
public class TokenFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return -9999;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        final HttpServletRequest request = context.getRequest();
        if (request.getServletPath().equals("/user/login")) {
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        System.out.println("context.getResponseBody() = " + context.getResponseBody());
        final InputStream responseDataStream = context.getResponseDataStream();
        InputStreamReader isr = new InputStreamReader(responseDataStream);
        char[] bytes = new char[1024];
        String body = null;
        try {
            final int c = isr.read(bytes);
            body = new String(bytes,0,c);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("body = " + body);
        if(body!=null){
            // 表示登录成功
            final HttpServletResponse response = context.getResponse();
            // 生成令牌 => JWT
            response.setHeader("Authorization","accessToken");
            context.setResponseBody(body);
        }
        return null;
    }
}
